import { shallowReactive, shallowRef } from 'vue'
import req from '../utils/req'
import { treeReplace } from '../utils/common'
import api from '../api'
export type OrgTreeItem = {
  code: string
  deptType: string
  enableFlag: boolean
  id: string
  name: string
  orgType: string
  parentId: string | null
  children: null | OrgTreeItem[]
}
export const dicts = shallowReactive<
  Record<
    string,
    {
      id: string
      itemCode: string
      itemName: string
      label: string
      value: string
      orderNum: number
      itemPcode: string
    }[]
  >
>({})
const dictsLoading: Record<string, boolean> = {}
const orgTree = shallowRef<OrgTreeItem[]>([])
let loading = false
async function getOrgTree(refresh = false) {
  if (loading) {
    return
  }
  loading = true
  if (!refresh && orgTree.value.length > 0) {
    return orgTree.value
  }
  try {
    const tree = await req.get(api.acmAuth.org.getAllEnableTree)

    orgTree.value = treeReplace(tree, { title: 'name', value: 'id', key: 'id' })
  } catch (error) {
    console.error(error)
  }
  loading = false
}

export async function getDict(code: string, refresh = false) {
  if (dictsLoading[code as string]) {
    return
  }
  dictsLoading[code as string] = true
  // @ts-ignore
  if (!refresh && dicts[code] && dicts[code].length > 0) {
    // @ts-ignore
    return dicts[code]
  }
  try {
    const res = await req.get(api.acmMdm.SysDictDefinition.queryItemByCode, { code })
    //  @ts-ignore
    dicts[code] = res.map((t: any) => ({
      ...t,
      label: t.itemName,
      value: t.itemCode
    }))
  } catch (error) {
    /* empty */
  }
  dictsLoading[code] = false
}

export default function useDict() {
  return { dicts, getDict, getOrgTree, orgTree }
}
